package com.myblog.config;

import com.myblog.entity.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义日志类
 */
@Configuration
@Aspect
@Slf4j //加上此注解可以省略logFactory实例化
public class LogAopConfig {
    //private static final Logger LOG = LoggerFactory.getLogger(LogConfig.class);

    @Pointcut("execution(* com.myblog.controller.*.*(..))")
    //@Pointcut("execution(* com.myblog.controller..*(..))") 包含controller/admin目录
    public void logPointcut() {
    }

    @Before("logPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Log requestLog = new Log(url, ip, classMethod, args);
        log.info("Request : {}", requestLog);
    }

    @AfterReturning(returning = "result", pointcut = "logPointcut()")
    public void doAfterRuturn(Object result) {
        log.info("Result  : {}", result);
    }

}
